#include	"tank.h"

#define		MAP_BUTTOM	-11.0
#define		MAP_TOP		 11.0
#define         MAX_MAP_NUM     20
#define         MAP_NAME_LEN    20

void
map_draw_tri(float x1, float y1, float x2, float y2, float x3, float y3)
{
	glBegin(GL_TRIANGLES);
		glTexCoord2f(x1, y1); glVertex2f(x1, y1);
		glTexCoord2f(x2, y2); glVertex2f(x2, y2);
		glTexCoord2f(x3, y3); glVertex2f(x3, y3);
	glEnd();
	return;
}

void
show_map(int n, float vertex[], float edge)
{
		float V[MAX_VERTEX];
        int i;
        for(i = 0; i < n / 2 - 1; i++) {
                V[4*i] = vertex[2*i];
                V[4*i+1] = vertex[2*i+1];
                V[4*i+2] = (vertex[2*i] + vertex[2*i+2]) / 2;
                V[4*i+3] = edge;
        }
        V[4*i] = vertex[2*i];
        V[4*i+1] = vertex[2*i+1];
	for(i = 0; i < 2 * (n - 3); i += 2) {
		map_draw_tri(V[i], V[i+1], V[i+2], V[i+3], V[i+4], V[i+5]);
	}
	map_draw_tri(V[0], V[1], V[0], edge, V[2], V[3]);
	map_draw_tri(V[2*n-6], V[2*n-5], V[2*n-4], edge, V[2*n-4], V[2*n-3]);
	return;
}

void
draw_start_point()
{
	glPushMatrix();
		glTranslatef(mapvertex[2], mapvertex[3] + 0.5, 0.0);
		glBegin(GL_QUADS);
			glTexCoord2f(0.0, 0.0); glVertex2f(0.0, 0.0);
			glTexCoord2f(1.0, 0.0); glVertex2f(0.2, 0.0);
			glTexCoord2f(1.0, 1.0); glVertex2f(0.2, 0.1);
			glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.1);
		glEnd();
	glPopMatrix();
	return;
}

void
draw_end_point()
{
	glPushMatrix();
		glTranslatef(mapvertex[vertex_count-4], mapvertex[vertex_count-3] + 0.5, 0.0);
		glBegin(GL_QUADS);
                        glTexCoord2f(0.0, 0.0); glVertex2f(0.0, 0.0);
                        glTexCoord2f(1.0, 0.0); glVertex2f(0.2, 0.0);
                        glTexCoord2f(1.0, 1.0); glVertex2f(0.2, 0.1);
                        glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.1);
                glEnd();
        glPopMatrix();
	return;
}

void
draw_map(int n, float vertex[])
{
	choosetex(grass_tex);	
	show_map(n, vertex, MAP_BUTTOM);
	choosetex(ground_tex);
	glPushMatrix();
	glTranslatef(0.00, -0.05, 0.00);
	show_map(n, vertex, MAP_BUTTOM);
	glPopMatrix();
	choosetex(sky_tex);
	show_map(n, vertex, MAP_TOP);
	choosetex(start_tex);
	draw_start_point();
	choosetex(end_tex);
	draw_end_point();
	choosetex(0);
	return;
}

void
load_map()
{
        FILE *fp;
        static int      map_count = 0;
        int             i = 0;
        char mapnames[MAX_MAP_NUM][MAP_NAME_LEN];
        fp = fopen("maps.conf", "r");
        while(fscanf(fp, "%s", mapnames[i])!=EOF) {
                if(i == MAX_MAP_NUM)
                        break;
                i++;
        }
        if(map_count < i) {
                read_map(mapnames[map_count], MAX_VERTEX);
                map_count++;
        } else {
                map_count = 0;
                read_map(mapnames[map_count], MAX_VERTEX);
                map_count++;
        }
        fclose(fp);
        return;
}

